<template>
  <div class="commonTableSty rightDrawerWithoutCol">
    <a-table
      :columns="columns"
      :rowKey="(record, index) => index"
      :dataSource="tableData"
      :pagination="false"
      :scroll="{ y: true ,x:900}"
      :components="tableComponents"
    >
      <template
        slot="name"
        slot-scope="text, record"
      >
        <a-input v-if="record.editable" v-model="record.name"></a-input>
        <table-ellipsis v-else :text="record.name"></table-ellipsis>
      </template>
      <template
        slot="remark"
        slot-scope="text, record"
      >
        <a-input v-if="record.editable" v-model="record.remarks"/>
        <table-ellipsis v-else :text="record.remarks||'-'"></table-ellipsis>
      </template>
      <template
        slot="operation"
        slot-scope="text, record,index"
      >
        <!-- 没有id或者是编辑状态展示“保存/取消” -->
        <template v-if="!record.id||record.editable">
          <a
            @click="saveEdit(record,index)"
          >{{ $t('save') }}</a>
          <a-divider type="vertical" />
          <a @click="handleCancle(record,index)">{{ $t('cancel') }}</a>
        </template>
        <!-- 编辑/删除 -->
        <template v-else>
          <!-- 编辑-->
          <a @click="handelEdit(record,index)">{{ $t('edit') }}</a>
          <!-- 删除 -->
          <a-divider type="vertical" />
          <a @click="deleteList(record)">{{ $t('delete') }}</a>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import { dictDataObj } from '../configConst'
import tableDraggable from '@/utils/tableDraggable'
import i18n from '@/lang'
const staticColum = [
  {
    title: '',
    key: 'name',
    width: 220,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: i18n.t('remark'),
    key: 'remark',
    width: 220,
    scopedSlots: { customRender: 'remark' }
  },
  {
    title: i18n.t('operation'),
    width: 120,
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  name: 'NewServiceBelongCate',
  components: {
    TableEllipsis,
    HasNoPermissionTip
  },
  props: {
    editWhich: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState({
      dictData: (state) => state.dict,
      instantUpdateTime: (state) => state.app.instantUpdateTime
    })
  },
  created () {
    this.tableComponents = tableDraggable(this.columns)
    this.columns[0].title = this.$t(this.editWhich)
  },
  watch: {
    instantUpdateTime: {
      handler () {
        this.$store.dispatch(dictDataObj[this.editWhich][2]).then(() => {
          this.tableData = this.$commonFun.deepCopy(this.dictData[dictDataObj[this.editWhich][0]])
          // 备份表格数据 用于取消
          this.backTableList = this.$commonFun.deepCopy(this.tableData)
        })
      },
      immediate: true
    }

  },
  data () {
    return {
      backTableList: [],
      tableData: [],
      tableComponents: {},
      columns: staticColum
    }
  },
  methods: {
    addList () {
      const objItem = {
        name: '',
        remarks: '',
        editable: true // 用于标识为编辑状态
      }
      this.tableData.unshift(objItem)
      this.backTableList.unshift(objItem)
    },
    saveEdit (record, index) {
      const vm = this
      let saveDictCode = {}
      //   名称不能为空
      if (!record.name.length || record.name.length > 20) {
        this.$message.warning('请输入名称且长度不能超过20字')
        return
      }
      if (record.remarks.length > 200) {
        this.$message.warning(vm.$t('length300'))
        return
      }
      const values = {
        dictCode: dictDataObj[this.editWhich][1],
        dictItemName: record.name,
        dictItemRemarks: record.remarks
      }
      // 考试地址
      if (this.examUrl === 'examUrl') {
        values.dictItemValue = record.name
      }
      if (record.id) {
        values.dictItemId = record.id
        saveDictCode = vm.$api.editDictCode(values)
      } else {
        saveDictCode = vm.$api.addDictCode(values)
      }
      saveDictCode
        .then((res) => {
          vm.$message.success(vm.$t('success'))
          // eslint-disable-next-line no-param-reassign
          record.editable = false
          if (!record.id) {
            vm.$set(record, 'id', res.data.id)
            vm.$set(record, 'value', res.data.value)
          }
          vm.backTableList[index] = { ...record } // 保存成功后同步备份
          // 清空服务归属域和服务分类字典
          vm.$store.commit('SET_DICT_CODE', { key: dictDataObj[vm.editWhich][0], val: [] })
        })
        .catch(() => {
          // eslint-disable-next-line no-param-reassign
          record.editable = true
          vm.$set(vm.backTableList[index], 'editable', true)
        })
    },
    handleCancle (record, index) {
      const vm = this
      this.$confirm({
        title: vm.$t('cancelSave'),
        content: vm.$t('cancelSaveTip'),
        onOk () {
          // eslint-disable-next-line no-param-reassign
          record.editable = false
          vm.$set(vm.backTableList[index], 'editable', false)
          if (record.id) {
            vm.$set(vm.tableData, index, vm.$commonFun.deepCopy(vm.backTableList[index]))
          } else {
            vm.tableData.splice(index, 1)
            vm.backTableList.splice(index, 1)
          }
        },
        onCancel () { }
      })
    },
    // 校验服务归属域或服务分类是否可以编辑或删除
    checkBelongcategory (record) {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$api.getCheckBelongcategory({ dictItemValue: record.value }).then(res => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 校验考试地址是否可以编辑或删除
    checkExamUrl (record) {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$api.getCheckExamUrl({ dictItemValue: record.name }).then(res => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    handelEdit (record, index) {
      const vm = this
      if(this.editWhich === 'examUrl'){
        vm.checkExamUrl(record).then((res) => {
          if (res.canDelOrEdit) {
            vm.$set(vm.tableData[index], 'editable', true)
            vm.$set(vm.backTableList[index], 'editable', true)
          } else {
            vm.$message.error(vm.$t('softEditTip2'))
          }
        })
      }else{
        vm.checkBelongcategory(record).then((res) => {
          if (res.canDelOrEdit) {
            vm.$set(vm.tableData[index], 'editable', true)
            vm.$set(vm.backTableList[index], 'editable', true)
          } else {
            vm.$message.error(vm.$t('softEditTip2'))
          }
        })
      }
    },
    checkDeleteBox(record,res){
      const vm = this
      if (res.canDelOrEdit) {
        this.$confirm({
          title: vm.$t('delete') + vm.$t(vm.editWhich),
          content: vm.$t('deleteConfirmNotice').replace('__CONTENT__', vm.$t(vm.editWhich)),
          class: 'confirmStyle',
          icon: '<Icon >',
          width: 378,
          onOk () {
            vm.$api.deleteDictCode({ ids: [record.id] }).then(() => {
              // 不能直接刷新列表否则新增中的更新文件被刷掉
              vm.tableData.splice(vm.tableData.findIndex(item => item.id === record.id), 1)
              vm.backTableList.splice(vm.backTableList.findIndex(item => item.id === record.id), 1)
              vm.$message.success(vm.$t('successfullyDelete'))
              // 清空服务归属域和服务分类字典
              vm.$store.commit('SET_DICT_CODE', { key: dictDataObj[vm.editWhich][0], val: [] })
            })
          },
          onCancel () { }
        })
      } else {
        vm.$message.error(vm.$t('softEditTip2'))
      }
    },
    deleteList (record) {
      const vm = this
      if(this.editWhich === 'examUrl'){
        vm.checkExamUrl(record).then((res) => {
          this.checkDeleteBox(record,res)
        })
      }else{
        vm.checkBelongcategory(record).then((res) => {
          this.checkDeleteBox(record,res)
        })
      }
    }
  }
}
</script>
